package com.unitedats.HR.Servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.unitedats.HR.Entity.HrDepartment;
import com.unitedats.common.Servlet.BasicServlet;
import com.unitedats.common.bo.Message;
import com.unitedats.common.util.DateUtil;
import com.unitedats.common.util.WebUtil;

public class DepartmentUpdateProcessServlet extends BasicServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String[] depIds = WebUtil.getParamValues(request, "depId");
		String[] depNames = WebUtil.getParamValues(request, "depName");

		if (depIds == null || depNames == null || depIds.length != depNames.length)
			throw new ServletException("Organization chart is not well formed");

		for (int i = 0; i < depIds.length; i++) {
			HrDepartment dep = dbm.findById(Integer.parseInt(depIds[i]), HrDepartment.class);
			if (!depNames[i].equals(dep.getName())) {
				dep.setName(depNames[i]);
				dep.setLastModifiedIn(DateUtil.getCurrentDate());
				dep.setLastModifiedBy(getSessionUser(request).getEmpId());
				dbm.mergeEntity(dep);
			}
		}

		setMessage(request,
				new Message("Organization chart has been updated successfuly", Message.MESSAGE_TYPE.SUCCESS));
		sendRedirect(request, response, "DepartmentUpdateDisplay");
	}
}
